from pms.common.views import PostFormula
from project.models import ProjectRole, Participate
from project.utils.role import project_role_view
from django.db.models.deletion import ProtectedError
from project.utils.permission import assert_project_permissions


class API(PostFormula):
    def handle(self, req):
        try:
            rid = req['rid']
            project_role = ProjectRole.objects.get(id=rid)
            assert_project_permissions(project_role.pid_id, self.user.id, [4])
            view = project_role_view(project_role)
            project_role.delete()
            return self.success_respond(view)
        except ProtectedError as e:
            protected_object = e.protected_objects.pop()
            if isinstance(protected_object, Participate):
                return self.failed_respond('PARTICIPATE_RID_PROTECT', '{}({}) 成员具有该项目身份，请先更改其项目身份'
                                           .format(protected_object.uid.name, protected_object.uid.id))
